package com.hzpd.hainan.module.news.fragment;

import android.app.ActivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.hzpd.hainan.R;
import com.hzpd.hainan.api.InterfaceJsonfile;
import com.hzpd.hainan.app.BaseFragment;
import com.hzpd.hainan.app.MyActivitymanager;
import com.hzpd.hainan.custorm.MyListView;
import com.hzpd.hainan.custorm.TopPicViewPager;
import com.hzpd.hainan.model.base.BaseEntity;
import com.hzpd.hainan.model.news.NewsBean;
import com.hzpd.hainan.model.news.NewsChannelBean;
import com.hzpd.hainan.model.news.NewsFlashBean;
import com.hzpd.hainan.model.news.NewsFlashEntity;
import com.hzpd.hainan.model.news.NewsListEntity;
import com.hzpd.hainan.module.news.adapter.NewsItemListViewAdapter;
import com.hzpd.hainan.module.news.adapter.TopviewpagerAdapter;
import com.hzpd.hainan.net.Factory;
import com.hzpd.hainan.utils.LogUtils;
import com.hzpd.hainan.utils.ParamUtils;
import com.hzpd.hainan.utils.TUtils;

import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.Unbinder;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by 猪猪侠 on 2017/7/3.
 */

public class NewsItemFragment extends BaseFragment {
    @BindView(R.id.test_pager)//顶部轮播
            TopPicViewPager testPager;
    @BindView(R.id.viewpage_txt_id)//轮播标题
            TextView viewpageTxtId;
    @BindView(R.id.viewpage_txt_Molecular)
    TextView viewpageTxtMolecular;
    @BindView(R.id.viewpage_txt_Denominator)
    TextView viewpageTxtDenominator;
    @BindView(R.id.news_viewpage_myroot)
    RelativeLayout newsViewpageMyroot;
    @BindView(R.id.news_item_listview)//新闻列表
            MyListView newsItemListview;
    @BindView(R.id.news_item_iv)//
            ImageView newsItemIv;
    @BindView(R.id.news_item_sv)
    PullToRefreshScrollView newsItemSv;//刷新
    Unbinder unbinder;
    private int position = -1;
    private NewsChannelBean channelbean;
    private int page = 1;
    private static final int pageSize = 15;//

    // 是否刷新最新数据
    private boolean mFlagRefresh;
    private boolean isContinue = true;//是否可以自动切换
    private boolean isNeedRefresh = false;
    private boolean isRefresh = false;//是否首次加载

    private MyRun switchTask;//切换线程
    private int interval = 4;//播放间隔时间

    private Handler viewHandler = new Handler();
    private TopviewpagerAdapter topAdapter;
    private String mTitle;
    private NewsItemListViewAdapter adapter;

    @Override
    public int setMyContentView() {
        return R.layout.news_prlistview;
    }


    public static final NewsItemFragment newInstance(int position, NewsChannelBean newsChannelBean) {
        NewsItemFragment fragment = new NewsItemFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putSerializable("bean", newsChannelBean);
        fragment.setArguments(bundle);
        return fragment;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    public void setTitle(String title) {
        mTitle = title;
    }

    public String getTitle() {
        return mTitle;
    }

    public void setIsNeedRefresh() {
        isNeedRefresh = true;
    }

    @Override
    public void initView() {
        channelbean = (NewsChannelBean) getArguments().getSerializable("bean");
        position = getArguments().getInt("position");
        newsItemSv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        adapter = new NewsItemListViewAdapter(activity);
        newsItemListview.setAdapter(adapter);
        newsItemSv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                refreshView.getLoadingLayoutProxy().setPullLabel("刷新中");
                page = 1;
                mFlagRefresh = true;
                getFlash();
                getServerList();

            }
            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                mFlagRefresh = false;
                page++;
                getServerList();

            }
        });
        newsItemListview.setOnItemClickListener(new MyListView.MyOnItemClickListener() {
            @Override
            public void onItemClick(ViewGroup parent, View view, int position, Object o) {
                NewsBean nb = (NewsBean) adapter.getItem(position);
                addCount(nb);
                MyActivitymanager.pushActivity(activity, nb, channelbean.getTid(), "newsitem");
            }
        });
        initFlash();
    }
    private void addCount(NewsBean nb){
        Map<String, String> map = new HashMap<>();
        map.put("nid", nb.getNid());
        Factory.provideHttpService()
                .newsAddCount(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<BaseEntity, Boolean>() {
                    @Override
                    public Boolean call(BaseEntity entity) {
                        LogUtils.i("addcount-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            return true;
                        }
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BaseEntity>() {
                    @Override
                    public void call(BaseEntity entity) {
                        LogUtils.i("addcount-->" + entity.msg);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtils.i("addcount-->失败" + throwable.toString());
                    }
                });

    }



    @Override
    public void initData() {

        if (0 == position || isNeedRefresh) {
            newsItemListview.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mFlagRefresh = true;
                    getServerList();
                    getFlash();
                }
            }, 800);
            isRefresh = true;
            isNeedRefresh = false;
        }

    }

    private void initFlash() {
        DisplayMetrics displayMetrics = activity.getResources().getDisplayMetrics();
        int height = (int) (displayMetrics.widthPixels * 0.58);
        topAdapter = new TopviewpagerAdapter(activity);
        topAdapter.setTid(channelbean.getTid());
        testPager.setAdapter(topAdapter);
        testPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == topAdapter.getCount() - 1) {
                    testPager.setCurrentItem(1, false);
                    return;
                } else if (0 == position) {
                    testPager.setCurrentItem(topAdapter.getCount() - 2, false);
                }
                viewpageTxtId.setText(topAdapter.getBean(position).getTitle());//设置小标题
                viewpageTxtMolecular.setText(topAdapter.getPosition(position) + "");
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    //获取幻灯
    private void getFlash() {
        LogUtils.i("init", "getflash");
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("tid", channelbean.getTid());
        Factory.provideHttpService()
                .newsFlashlist(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsFlashEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsFlashEntity entity) {
                        LogUtils.i("flash--200-->" + entity.code);
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200-->成功");
                            return true;
                        }
                        LogUtils.i("flash--200失败");
                        return false;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsFlashEntity>() {
                    @Override
                    public void call(NewsFlashEntity entity) {
                        newsItemSv.onRefreshComplete();
                        LogUtils.i("flash--200-->成功");
                        try {
                            interval = Integer.parseInt(entity.data.interval) != 0 ? Integer.parseInt(entity.data.interval) : 4;
                        } catch (Exception e) {
                        }
                        setFlashData(entity.data.flash);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        newsItemSv.onRefreshComplete();
                        LogUtils.i("flash--200-->失败" + throwable.toString());
                    }
                });


    }

    private void setFlashData(List<NewsFlashBean> mViewPagelist) {
        LogUtils.i("pagelist_size" + mViewPagelist.size());
        if (null == mViewPagelist || mViewPagelist.size() < 1) {
            newsViewpageMyroot.setVisibility(View.GONE);
            return;
        }
        LogUtils.i("visbial");
        newsViewpageMyroot.setVisibility(View.VISIBLE);
        viewHandler.removeCallbacksAndMessages(null);
        switchTask = new MyRun();
        testPager.setCurrentItem(0);

        LogUtils.i("mViewPagelist-->" + mViewPagelist.size());

        viewpageTxtId.setText(mViewPagelist.get(0).getTitle());

        topAdapter.setData(mViewPagelist);

        viewpageTxtMolecular.setText("1");
        if (mViewPagelist.size() > 1) {
            viewpageTxtDenominator.setText("/" + (mViewPagelist.size() - 2));
            testPager.setCurrentItem(1, false);
        } else {
            viewpageTxtDenominator.setText("/" + mViewPagelist.size());
        }

        if (topAdapter.getListSize() > 1) {
            switchTask.run();
        }

    }

    public void init() {
        LogUtils.i("init-->"+newsItemListview);
        LogUtils.i("init-->"+isRefresh);
        if (!isRefresh && null != newsItemListview) {
            newsItemListview.postDelayed(new Runnable() {
                @Override
                public void run() {
                    LogUtils.i("init-->shuaxin");
                    newsItemSv.setRefreshing(true);
                    isRefresh = true;
                }
            }, 600);
        }
    }

    /**
     * 获取新闻数据
     */
    public void getServerList() {
        LogUtils.i("init", "getNewslist");
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("tid", channelbean.getTid());
        map.put("Page", page + "");
        map.put("PageSize", pageSize + "");
        Factory.provideHttpService()
                .newslist(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsListEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsListEntity entity) {

                        if ("200".equals(entity.code)) {
                            LogUtils.i("200--list>成功");
                            return true;
                        }
                        LogUtils.i("200--list>失败");
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsListEntity>() {
                    @Override
                    public void call(NewsListEntity entity) {
                        newsItemSv.onRefreshComplete();
                        if ("200".equals(entity.code)) {
                            LogUtils.i("200--list>成功");
                            setListData(entity.data);
                            if (mFlagRefresh){
                                LogUtils.i("200-->saveAll");
                                DataSupport.saveAll(entity.data);
                            }

                        }else {
                            TUtils.toast(entity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        if (mFlagRefresh){
                            setListData(DataSupport.where("tid=?",channelbean.getTid()).find(NewsBean.class));
                        }
                        newsItemSv.onRefreshComplete();
                        LogUtils.i("200--list>失败" + throwable.toString());
                    }
                });


    }

    public void setListData(List<NewsBean> list) {
        adapter.appendData(list, mFlagRefresh);
        adapter.notifyDataSetChanged();
        newsItemListview.setAdapter(adapter);
        newsItemSv.setMode(PullToRefreshBase.Mode.BOTH);
    }
/**
 * 轮播定时滚动
 */
    /**
     * 轮播定时滚动
     */
    class MyRun implements Runnable {
        private boolean isStart = false;

        public void run() {
            if (isContinue && isStart) {

                int current = testPager.getCurrentItem();
                int total = testPager.getAdapter().getCount();
                if (total == current + 1) {
                    testPager.setCurrentItem(0, false);
                } else {
                    testPager.setCurrentItem(current + 1, true);
                }
            } else {
                isStart = true;
            }

            viewHandler.postDelayed(switchTask, interval * 1000);
        }
    }

    @Override
    public void onDestroy() {
        if (null != viewHandler) {
            viewHandler.removeCallbacks(switchTask);
        }
        super.onDestroy();

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null) {
            unbinder.unbind();
        }

    }
}
